<template>
  <div class="login-container">
    <el-card class="login-card">
      <div slot="header" class="login-header">
        <h2>用户管理系统</h2>
        <p>请登录后继续操作</p>
      </div>
      <el-form 
        :model="loginForm" 
        :rules="rules" 
        ref="loginForm" 
        label-width="80px" 
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" class="login-btn">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    async handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            // 调用登录API
            const response = await login(this.loginForm)
            // 登录成功，存储token
            localStorage.setItem('token', response.data.token)
            this.$router.push('/user-management')
            this.$message.success('登录成功')
          } catch (error) {
            this.$message.error(error.response?.data?.message || '登录失败，请检查用户名和密码')
          } finally {
            this.loading = false
          }
        }
      })
    }
  },
  mounted() {
    // 如果已经登录，直接跳转到用户管理页面
    if (localStorage.getItem('token')) {
      this.$router.push('/user-management')
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #2b4b6b;
  background-image: 
    radial-gradient(circle at 10% 20%, rgba(255,255,255,0.05) 0%, transparent 20%),
    radial-gradient(circle at 90% 80%, rgba(255,255,255,0.05) 0%, transparent 20%);
}

.login-card {
  width: 400px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  overflow: hidden;
}

.login-header {
  text-align: center;
  padding: 20px 0;
}

.login-header h2 {
  margin: 0 0 10px 0;
  color: #1890ff;
}

.login-header p {
  margin: 0;
  color: #666;
}

.login-form {
  padding: 0 30px 30px 30px;
}

.login-btn {
  width: 100%;
}
</style>
